package com.lingkang.cpm.config;

import com.lingkang.cpm.config.impl.CustomUserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author 绫小路
 * @Date 2021/4/1
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  //注入我们加密的方式，spring5+以上必须要加密密码，这是官网推荐的加密方式，也可选择MD5
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public UserDetailsService userDetailsService(){
    return new CustomUserDetailsServiceImpl();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    //授权规则，除了要授权的，其他所有人能访问
    http.authorizeRequests()
        .antMatchers("/admin/**").hasAnyRole("ADMIN")
        .antMatchers("/user/**").hasAnyRole("USER")
        .anyRequest().permitAll(); //其他页面所有人能访问

    //自定义登陆返回的结果，用于ajax异步
//    http.formLogin().successHandler(authenticationSuccessHandler)
//        .failureHandler(authenticationFailureHandler).permitAll();


    //注销功能 ,跳回首页
    //关闭跨域认证请求，否则你需要post来注销
    http.logout().logoutSuccessUrl("/")
        .and().csrf().disable()
        .headers().frameOptions().disable();//允许使用iframe

    //启动登陆页面
    //定制登陆页面，表单提交的路径loginProcessingUrl
    http.formLogin().loginPage("/login").loginProcessingUrl("/login");

  }
}
